// 简单HTTP服务器示例 - 演示如何使用原生Java创建HTTP端口并处理请求

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

// 简单的HTTP服务器实现
public class SimpleHttpServer {
    
    private HttpServer server;
    private ObjectMapper objectMapper = new ObjectMapper();
    
    // 启动HTTP服务器
    public void startServer(int port) throws IOException {
        // 创建HTTP服务器实例，绑定到指定端口
        server = HttpServer.create(new InetSocketAddress(port), 0);
        
        // 创建线程池来处理并发请求
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
        
        // 注册不同的请求处理器
        server.createContext("/api/users", new UsersHandler());
        server.createContext("/api/products", new ProductsHandler());
        server.createContext("/", new RootHandler());
        
        // 设置线程池
        server.setExecutor(threadPoolExecutor);
        
        // 启动服务器
        server.start();
        System.out.println("服务器启动成功，监听端口: " + port);
    }
    
    // 停止HTTP服务器
    public void stopServer() {
        server.stop(0);
        System.out.println("服务器已停止");
    }
    
    // 根路径处理器
    static class RootHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // 只处理GET请求
            if (!"GET".equals(exchange.getRequestMethod())) {
                sendErrorResponse(exchange, 405, "请求方法不被允许");
                return;
            }
            
            // 构造欢迎信息的JSON响应
            List<String> endpoints = Arrays.asList(
                "/api/users - 用户信息接口",
                "/api/products - 商品信息接口"
            );
            
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("message", "欢迎使用简单HTTP服务器");
            responseData.put("endpoints", endpoints);
            responseData.put("status", "success");
            
            sendJsonResponse(exchange, 200, responseData);
        }
    }
    
    // 用户信息处理器
    class UsersHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String requestMethod = exchange.getRequestMethod();
            
            // 处理GET请求 - 获取用户列表
            if ("GET".equals(requestMethod)) {
                // 创建用户数据
                List<User> users = Arrays.asList(
                    new User(1, "张三", "zhangsan@example.com", 25),
                    new User(2, "李四", "lisi@example.com", 30)
                );
                
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("users", users);
                responseData.put("total", users.size());
                
                sendJsonResponse(exchange, 200, responseData);
            } 
            // 处理POST请求 - 创建新用户
            else if ("POST".equals(requestMethod)) {
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("message", "用户创建成功");
                responseData.put("userId", 3);
                responseData.put("status", "success");
                
                sendJsonResponse(exchange, 201, responseData);
            } 
            // 不支持的请求方法
            else {
                sendErrorResponse(exchange, 405, "请求方法不被允许");
            }
        }
    }
    
    // 商品信息处理器
    class ProductsHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String requestMethod = exchange.getRequestMethod();
            
            // 处理GET请求 - 获取商品列表
            if ("GET".equals(requestMethod)) {
                // 检查是否有查询参数
                String queryString = exchange.getRequestURI().getQuery();
                Map<String, String> params = parseQueryParams(queryString);
                
                // 创建商品数据
                List<Product> products = Arrays.asList(
                    new Product(1, "笔记本电脑", 5999.99, "电子产品"),
                    new Product(2, "无线鼠标", 99.99, "电子产品")
                );
                
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("products", products);
                responseData.put("total", products.size());
                
                sendJsonResponse(exchange, 200, responseData);
            } 
            // 不支持的请求方法
            else {
                sendErrorResponse(exchange, 405, "请求方法不被允许");
            }
        }
    }
    
    // 发送JSON HTTP响应的工具方法
    private static void sendJsonResponse(HttpExchange exchange, int statusCode, Object data) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(data);
        
        // 设置响应头，声明内容类型为JSON
        exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
        
        // 将响应字符串转换为字节数组
        byte[] responseBytes = jsonResponse.getBytes("UTF-8");
        
        // 发送响应头和状态码
        exchange.sendResponseHeaders(statusCode, responseBytes.length);
        
        // 发送响应体
        OutputStream outputStream = exchange.getResponseBody();
        outputStream.write(responseBytes);
        outputStream.close();
    }
    
    // 发送错误响应的工具方法
    private static void sendErrorResponse(HttpExchange exchange, int statusCode, String errorMessage) throws IOException {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", errorMessage);
        
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(errorResponse);
        
        // 设置响应头，声明内容类型为JSON
        exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
        
        // 将响应字符串转换为字节数组
        byte[] responseBytes = jsonResponse.getBytes("UTF-8");
        
        // 发送响应头和状态码
        exchange.sendResponseHeaders(statusCode, responseBytes.length);
        
        // 发送响应体
        OutputStream outputStream = exchange.getResponseBody();
        outputStream.write(responseBytes);
        outputStream.close();
    }
    
    // 解析查询参数的工具方法
    private static Map<String, String> parseQueryParams(String query) {
        Map<String, String> queryParams = new HashMap<>();
        if (query != null && !query.isEmpty()) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    queryParams.put(keyValue[0], keyValue[1]);
                }
            }
        }
        return queryParams;
    }
    
    // 主方法 - 启动服务器
    public static void main(String[] args) {
        SimpleHttpServer httpServer = new SimpleHttpServer();
        try {
            // 启动服务器，监听8080端口
            httpServer.startServer(8080);
            
            // 添加关闭钩子，确保服务器能够优雅关闭
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                httpServer.stopServer();
            }));
            
            System.out.println("服务器正在运行... 按 Ctrl+C 停止服务器");
            
            // 保持主线程运行
            Thread.currentThread().join();
            
        } catch (IOException e) {
            System.err.println("启动服务器时发生错误: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("服务器被中断");
        }
    }
}